<template>
	<div class="login-page">
    <m-header class="header">
      <div slot="middle" class="tab">
        <span>手机号登陆</span>
      </div>
      <div slot="left" @click="$router.replace('login')">
        <i class="iconfont icon-xiangzuo" />
      </div>
    </m-header>
		<div class="inner">
			<span class="tip">未注册手机号登陆后将自动创建账号</span>
			<div class="input-warpper border-1px-bottom">
				<div class="area" @click="show = true">
					<div>
						<span>+{{ selectCountry.code }}</span>
						<i class="iconfont icon-jiantou_xia" />
					</div>
				</div>
				<van-field
					v-model="phone"
					type="number"
					clearable
					placeholder="请输入手机号"
					class="field"
					autofocus
					maxlength='11'
				/>
			</div>
			<van-button :loading='loading' round type="danger" size="small" block @click="next">下一步</van-button>
		</div>

		<van-popup v-model="show" position="bottom" :lock-scroll="false" class="popup">
			<index-bar ref="indexBar"
								@clickItem='clickItem'
								:list='countries'
			>
				<div slot-scope="{item}" class="border-1px-bottom index-bar__item">
					<span>{{ item.zh }}</span>
					<span class="code">+{{ item.code }}</span>
				</div>
			</index-bar>
		</van-popup>
	</div>
</template>

<script>
import MHeader from 'base/m-header'
import IndexBar from 'base/index-bar'
import { list } from 'api/countries'
import { check } from 'api/cellphone'

export default {
	components: {
		MHeader,
		IndexBar
	},
	data() {
		return {
			phone: '',
			show: false,
			countries: [],
			loading: false,
			selectCountry: {
				code: "86",
				en: "China",
				locale: "CN",
				zh: "中国"
			}
		}
	},
	mounted() {
		this.getCountriesList()
	},
	methods: {
		getCountriesList() {
			list().then(res => {
				this.countries = this.normalization(res.data || [])
			})
		},
		normalization(list) {
			return list.map(item => {
				const items = item.countryList.map(it => {
					return {
						...it,
						text: it.zh
					}
				})
				return {
					title: item.label.substr(0, 1),
					items
				}
			})
		},
		checkPhone(phone) {
			return /^1(3|4|5|7|8)\d{9}$/.test(phone)
		},
		next() {
			if (!this.checkPhone(this.phone)) {
				this.$toast('请输入正确手机号码')
				return
			}

			this.loading = true
			check(this.phone, this.selectCountry.code).then(res => {
				if (res.hasPassword) { // 有没有密码
					// 登陆
					this.$router.push({
						name: 'password',
						params: {
							phone: this.phone
						}
					})
				} else {
					// 发验证码
				}
			}).finally(() => {
				this.loading = false
			})
		},
		clickItem(item) {
			this.selectCountry = item
			this.show = false
		}
	}
}
</script>
<style lang="less" scoped>
@import './style/index.less';
</style>